package com.hig.risk.service.impl;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;

import com.hig.risk.domain.RiskScoreControl;
import com.hig.risk.mapper.RiskScoreControlMapper;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hig.risk.mapper.RiskHazardSourceMapper;
import com.hig.risk.domain.RiskHazardSource;
import com.hig.risk.service.IRiskHazardSourceService;

/**
 * 危险源管理Service业务层处理
 * 
 * @author scp
 * @date 2024-09-25
 */
@Service
public class RiskHazardSourceServiceImpl implements IRiskHazardSourceService 
{
    @Autowired
    private RiskHazardSourceMapper riskHazardSourceMapper;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private RiskScoreControlMapper riskScoreControlMapper;

    /**
     * 查询危险源管理
     * 
     * @param id 危险源管理ID
     * @return 危险源管理
     */
    @Override
    public RiskHazardSource selectRiskHazardSourceById(Long id)
    {
        return riskHazardSourceMapper.selectRiskHazardSourceById(id);
    }

    /**
     * 查询危险源管理列表
     * 
     * @param riskHazardSource 危险源管理
     * @return 危险源管理
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<RiskHazardSource> selectRiskHazardSourceList(RiskHazardSource riskHazardSource)
    {
        return riskHazardSourceMapper.selectRiskHazardSourceList(riskHazardSource);
    }

    /**
     * 新增危险源管理
     * 
     * @param riskHazardSource 危险源管理
     * @return 结果
     */
    @Override
    public int insertRiskHazardSource(RiskHazardSource riskHazardSource)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
//        riskHazardSource.setCreateBy(loginUser.getUser().getUserName());
//        riskHazardSource.setDeptId(loginUser.getUser().getDeptId());
        riskHazardSource.setCreateTime(DateUtils.getNowDate());
        return riskHazardSourceMapper.insertRiskHazardSource(riskHazardSource);
    }

    /**
     * 修改危险源管理
     * 
     * @param riskHazardSource 危险源管理
     * @return 结果
     */
    @Override
    public int updateRiskHazardSource(RiskHazardSource riskHazardSource)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        riskHazardSource.setUpdateBy(loginUser.getUser().getUserName());
        riskHazardSource.setUpdateTime(DateUtils.getNowDate());
        return riskHazardSourceMapper.updateRiskHazardSource(riskHazardSource);
    }

    /**
     * 批量删除危险源管理
     * 
     * @param ids 需要删除的危险源管理ID
     * @return 结果
     */
    @Override
    public int deleteRiskHazardSourceByIds(Long[] ids)
    {
        //同时删除对应的风险分级管控
        riskScoreControlMapper.deleteRiskScoreControlSourceByIds(ids);
        return riskHazardSourceMapper.deleteRiskHazardSourceByIds(ids);
    }

    /**
     * 删除危险源管理信息
     * 
     * @param id 危险源管理ID
     * @return 结果
     */
    @Override
    public int deleteRiskHazardSourceById(Long id)
    {
        return riskHazardSourceMapper.deleteRiskHazardSourceById(id);
    }

    @Override
    @DataScope(deptAlias = "d")
    public List<RiskHazardSource> selectSourceAll(RiskHazardSource riskHazardSource) {
        return riskHazardSourceMapper.selectSourceAll(riskHazardSource);
    }

    @Override
    public int checkRiskHazardSource(Long[] ids) {
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = dateFormat.format(now);
        for (Long id : ids) {
            RiskHazardSource source = new RiskHazardSource();
            source.setId(id);
            source.setRemarkSpare1(formattedDate);
            riskHazardSourceMapper.updateRiskHazardSource(source);
        }
        return 1;
    }

    @Override
    @DataScope(deptAlias = "d")
    public AjaxResult selectOvertime(RiskHazardSource riskHazardSource) {
        try {
            String notEntered = "";
            String overtime = "";
            //查询所有危险源
            List<RiskHazardSource> list = riskHazardSourceMapper.selectRiskHazardSourceList(riskHazardSource);
            String warningDaysKey = configService.selectConfigByKey("source.warning.days");
            long warningDays = Long.parseLong(warningDaysKey);
            for (RiskHazardSource source : list) {
                if (source.getRemarkSpare1() != null) {
                    String str = source.getRemarkSpare1();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    Date revisionTime = sdf.parse(str);
                    LocalDate productionDate = revisionTime.toInstant()
                            .atZone(ZoneId.systemDefault())
                            .toLocalDate();
                    LocalDate today = LocalDate.now();
                    long daysSinceProduction = ChronoUnit.DAYS.between(productionDate, today);
                    if (daysSinceProduction >= warningDays) {
                        overtime += source.getHazardName() + ",";
                    }
                } else {
                    notEntered += source.getHazardName() + ",";
                }
            }
            String msg = "";
            if (overtime.length() > 0) {
                overtime = overtime.substring(0, overtime.length() - 1);
                msg += overtime + "超过" + warningDays + "天未确认，请确认风险！";
            }
            if (notEntered.length() > 0) {
                notEntered = notEntered.substring(0, notEntered.length() - 1);
                msg += notEntered + "未确认，请确认风险！";
            }
            if (msg.length() > 0) {
                return AjaxResult.error(msg);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return AjaxResult.success();
    }
}
